package com.niannian.activity;

import java.io.File;
import java.util.Calendar;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import com.niannian.BaseActivity;
import com.niannian.MyApplication;
import com.niannian.R;
import com.niannian.adapter.NumericWheelAdapter;
import com.niannian.adapter.OnWheelScrollListener;
import com.niannian.dialog.SelectPhotoDialog;
import com.niannian.dialog.TipDialog;
import com.niannian.dialog.TipDialog.onSimpleOnCancelListener;
import com.niannian.dialog.TipDialog.onSimpleOnClicklListener;
import com.niannian.util.BitmapUtil;
import com.niannian.util.AsyncHandle;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MyTextWatcher;
import com.niannian.util.Sys;
import com.niannian.util.VAR;
import com.niannian.view.WheelView;
import com.niannian.web.nnSyncApi;

/**
 * 
 * 注册第三步 填写资料
 * 
 * @author shengl
 * 
 */
public class RegisterThereActivity extends BaseActivity {
	private EditText userName;
	private ImageView userHeadView, reg_head_img_p;
	private TextView userBrithday;
	private RadioButton userMan;
	private RadioButton userWoman;
	private Button userRegisterNextStep;

	private TipDialog tip;
	private View brithdayView;
	private PopupWindow popup;
	private final int year_start = 1920;

	private String brithday = "";

	private File phoneSavePath = null;
	String nickname = "";
	String gender = "U";
	String avatar = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register_three);
		initView();
		setLister();
		initDialog();
		initTopView();
		// String uri =
		// "http://d.hiphotos.baidu.com/image/pic/item/4b90f603738da9772a1d41e4b251f8198718e3cb.jpg";

		// myApplication.finalbitmap.display(userHeadView, uri);
	}

	private MyTextWatcher TextWatcheruser = new MyTextWatcher() {

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			String name = userName.getText().toString().trim();
			String Brithday = userBrithday.getText().toString().trim();
			// if (!Common.empty(name) && !Common.empty(Brithday) &&
			// (userMan.isChecked() || userWoman.isChecked())) {
			if (!Common.empty(name)) {
				//userRegisterNextStep.setEnabled(true);
			} else {
				//userRegisterNextStep.setEnabled(false);
			}
		}
	};

	private void initDialog() {
		tip = new TipDialog(RegisterThereActivity.this, "确认要放弃完善社交名片吗?");
		tip.setOnCancelListener(new onSimpleOnCancelListener() {

			@Override
			public void onCancel() {
				tip.dismiss();
			}
		});
		tip.setOnConfimClickListener(new onSimpleOnClicklListener() {

			@Override
			public void onClick() {
				openActivity(LoginBeforeActivity.class);
				myfinish();
				tip.dismiss();
			}
		});
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);
		top_title.setText("完善资料");

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.GONE);

		iv_top_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openActivity(LoginBeforeActivity.class);
				myfinish();
				// tip.show();
			}
		});
	}

	@Override
	public void onBackPressed() {
		openActivity(LoginBeforeActivity.class);
		myfinish();
		// tip.show();
	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		userHeadView = (ImageView) findViewById(R.id.reg_head_img);
		reg_head_img_p = (ImageView) findViewById(R.id.reg_head_img_p);
		userName = (EditText) findViewById(R.id.reg_name);
		userMan = (RadioButton) findViewById(R.id.rd_man);
		userWoman = (RadioButton) findViewById(R.id.rd_woman);
		userBrithday = (TextView) findViewById(R.id.rg_brithday);
		userRegisterNextStep = (Button) findViewById(R.id.btn_register_complete);
		userName.addTextChangedListener(TextWatcheruser);
		userBrithday.addTextChangedListener(TextWatcheruser);
	}

	/**
	 * 为按钮添加监听事件
	 */
	private void setLister() {

		userMan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// String name = userName.getText().toString().trim();
				// String Brithday = userBrithday.getText().toString().trim();
				// if (!Common.empty(name) && !Common.empty(Brithday)) {
				// userRegisterNextStep.setEnabled(true);
				// } else {
				// userRegisterNextStep.setEnabled(false);
				// }

			}
		});

		userWoman.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// String name = userName.getText().toString().trim();
				// String Brithday = userBrithday.getText().toString().trim();
				// if (!Common.empty(name) && !Common.empty(Brithday)) {
				// userRegisterNextStep.setEnabled(true);
				// } else {
				// userRegisterNextStep.setEnabled(false);
				// }
			}
		});

		userRegisterNextStep.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				nickname = userName.getText().toString();
				if (userMan.isChecked()) {
					gender = "M";
				}
				if (userWoman.isChecked()) {
					gender = "F";
				}
				brithday = userBrithday.getText().toString();

				int checkName = Common.checkName(nickname);
				switch (checkName) {
				case -1:
					Common.tip(RegisterThereActivity.this, "名字只能是汉字、数字、字母组合");
					return;
				case -2:
					Common.tip(RegisterThereActivity.this, "昵称长度不符合要求");
					return;
				}
				new uploadUserinfo().init(RegisterThereActivity.this, null, true, "资料修改中...").execute();
			}
		});

		reg_head_img_p.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				phoneSavePath = new File(MyApplication.FILE_PATH_IMAGES_BIG + userInfoManager.id + "headtemp.jpg");
				SelectPhotoDialog dialog = new SelectPhotoDialog(RegisterThereActivity.this, R.style.MyDialogStyle, phoneSavePath);
				dialog.show();
			}
		});

		userBrithday.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				brithdayView = LayoutInflater.from(RegisterThereActivity.this).inflate(R.layout.year_month_day, null);
				TextView title = (TextView) brithdayView.findViewById(R.id.wheel_title);
				final WheelView year = (WheelView) brithdayView.findViewById(R.id.wheel_year);
				final WheelView month = (WheelView) brithdayView.findViewById(R.id.wheel_month);
				final WheelView day = (WheelView) brithdayView.findViewById(R.id.wheel_day);

				title.setText("选择生日");
				String tm = userBrithday.getText().toString();
				/*
				 * if (TextUtils.isEmpty(tm)) { tm = "1990/1/1"; }
				 */
				Calendar old = Sys.StringToDate(tm, "yyyy-MM-dd");
				int tmp_year = old.get(Calendar.YEAR);
				int tmp_month = old.get(Calendar.MONTH) + 1;
				int tmp_day = old.get(Calendar.DAY_OF_MONTH);

				Calendar c = Calendar.getInstance();

				year.setAdapter(new NumericWheelAdapter(year_start, c.get(Calendar.YEAR), "%02d", "年"));

				year.setCyclic(true);
				year.setCurrentItem(tmp_year - year_start);

				month.setAdapter(new NumericWheelAdapter(1, 12, "%02d", "月"));
				month.setCyclic(true);
				month.setCurrentItem(tmp_month - 1);

				day.setAdapter(new NumericWheelAdapter(1, c.getActualMaximum(Calendar.DAY_OF_MONTH), "%02d", "日"));
				day.setCyclic(true);
				day.setCurrentItem(tmp_day - 1);

				year.addScrollingListener(new OnWheelScrollListener() {

					@Override
					public void onScrollingStarted(WheelView wheel) {
					}

					@Override
					public void onScrollingFinished(WheelView wheel) {
						Calendar tmp = Calendar.getInstance();
						int _year_index = year.getCurrentItem();
						int _month_index = month.getCurrentItem();
						tmp.set(Calendar.YEAR, _year_index + year_start);
						tmp.set(Calendar.MONTH, _month_index);
						int _max_day_of_month = tmp.getActualMaximum(Calendar.DAY_OF_MONTH);
						day.setAdapter(new NumericWheelAdapter(1, _max_day_of_month, "%02d", "日"));

						if (day.getCurrentItem() > _max_day_of_month - 1) {
							day.setCurrentItem(0);
						}
					}
				});

				month.addScrollingListener(new OnWheelScrollListener() {

					@Override
					public void onScrollingStarted(WheelView wheel) {
					}

					@Override
					public void onScrollingFinished(WheelView wheel) {
						Calendar tmp = Calendar.getInstance();
						int _year_index = year.getCurrentItem();
						int _month_index = month.getCurrentItem();
						tmp.set(Calendar.YEAR, _year_index + year_start);
						tmp.set(Calendar.MONTH, _month_index);
						int _max_day_of_month = tmp.getActualMaximum(Calendar.DAY_OF_MONTH);
						day.setAdapter(new NumericWheelAdapter(1, _max_day_of_month, "%02d", "日"));

						if (day.getCurrentItem() > _max_day_of_month - 1) {
							day.setCurrentItem(0);
						}
					}
				});

				Button btn_ok = (Button) brithdayView.findViewById(R.id.btn_ok);
				btn_ok.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						int nYear = year.getCurrentItem() + year_start;
						int nMonth = month.getCurrentItem() + 1;
						int nDay = day.getCurrentItem() + 1;
						userBrithday.setText(String.format("%02d-%02d-%02d", nYear, nMonth, nDay));
						popup.dismiss();
					}
				});

				Button btn_cancel = (Button) brithdayView.findViewById(R.id.btn_cancel);
				btn_cancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						popup.dismiss();
					}
				});

				popup = new PopupWindow(brithdayView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				popup.setBackgroundDrawable(new BitmapDrawable());
				popup.setAnimationStyle(R.style.ModePopupAnimation);
				popup.setOutsideTouchable(true);
				popup.setFocusable(true);

				popup.showAtLocation(userBrithday, Gravity.CENTER, 0, 0);

			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		if (id == 0) {
			Calendar c = null;
			c = Calendar.getInstance();
			dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

				@Override
				public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
					month++;
					userBrithday.setText(year + "/" + month + "/" + dayOfMonth);
				}

			}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
			return dialog;
		}
		return dialog;
	}

	private void imageCrop(String headpath) {
		Intent i = new Intent(RegisterThereActivity.this, ImageFilterCropActivity.class);
		i.putExtra("path", headpath);
		startActivityForResult(i, VAR.PHOTO_OK);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (RESULT_OK != resultCode) {
			return;
		}

		if (requestCode == VAR.PHOTO_HRAPH) {
			try {
				imageCrop(phoneSavePath.getAbsolutePath());
			} catch (Exception e) {
				e.printStackTrace();
			}

			return;
		}

		if (requestCode == VAR.PHOTO_ALBUM) {
			try {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				if (cursor != null) {
					int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					if (cursor.getCount() > 0 && cursor.moveToFirst()) {
						String path = cursor.getString(column_index);
						imageCrop(path);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (requestCode == VAR.PHOTO_OK) {
			String imagePath = data.getStringExtra("path");
			Log.i(VAR.LEVEL_INFO, imagePath);
			if (!Common.empty(imagePath)) {
				try {
					Bitmap headimage = BitmapUtil.getSmallBitmap(imagePath);
					userHeadView.setImageBitmap(headimage);

					avatar = MyApplication.FILE_PATH_TEMP + userInfoManager.id + "headtemp.jpg";

					File file = new File(avatar);
					if (file.exists()) {
						file.delete();
					}

					BitmapUtil.saveBmp(headimage, avatar, 50);
					file = new File(avatar);
					if (!file.exists()) {
						Common.tip(RegisterThereActivity.this, "图片保存失败");
					}

				} catch (Exception e) {
					Common.tip(RegisterThereActivity.this, "图片保存失败");
				}
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	protected class uploadUserinfo extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {

			Common.tip(RegisterThereActivity.this, "资料修改失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				Common.tip(RegisterThereActivity.this, "资料修改成功");

				try {
					JSONObject userJson = paramJSONObject.getJSONObject("data");
					userInfoManager.Json2DBUser(userJson);
					update_gUser();
					openActivity(HomeActivity.class);
					myfinish();
					return;

				} catch (Exception e) {
					// TODO: handle exception
				}

			} else {
				Common.tip(RegisterThereActivity.this, paramJSONObject.getString("msg"));
			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.updateFamilyUserinfo(userInfoManager.id, nickname, null, null, null, gender, avatar, brithday);
		}
	}
}
